import React, {Component} from 'react';
import {Menu} from 'antd';
import './index.less';
import {Link, withRouter} from 'react-router-dom';
import {IconFont} from '../../utils/config';
import menuList from "../../utils/menuConfig";

const {SubMenu} = Menu;

class LeftNav extends Component {
  state = {
    openKeys: [], // 当前展开的 SubMenu 菜单项 key 数组
  }

  getMenu = (menuList) => {
    return menuList.map(item => {
      if (item.children) {
        return (
          <SubMenu key={item.key} icon={<IconFont type={item.icon}/>} title={item.title}>
            {this.getMenu(item.children)}
          </SubMenu>
        )
      }
      return (
        <Menu.Item key={item.key} icon={<IconFont type={item.icon}/>}>
          <Link to={item.key}>
            {item.title}
          </Link>
        </Menu.Item>
      )
    })
  }
  // 默认展开subMenu
  getOpenKey = (pathname) => {
    const arr = menuList.filter(item => item.children);
    for (let i of arr) {
      if (i.children.find(item => item.key === pathname)) {
        this.setState({openKeys: [i.key]})
      }
    }
  }

  componentDidMount() {
    this.getOpenKey(this.props.location.pathname)
  }

  // 只展开当前父级
  onOpenChange = (keys) => {
    let openKeys = this.state.openKeys;
    const latestOpenKey = keys.find(key => openKeys.indexOf(key) === -1); // 获取最新的keys
    this.setState({openKeys: [latestOpenKey]});
  }

  render() {
    const pathname = this.props.location.pathname;
    const {openKeys} = this.state;

    return (
      <div className='left-nav'>
        {/*显示menu*/}
        <Menu
          defaultSelectedKeys={[pathname]}
          onOpenChange={this.onOpenChange}
          openKeys={openKeys}
          mode="inline"
        >
          {this.getMenu(menuList)}
        </Menu>
      </div>
    )
  }
}

export default withRouter(LeftNav);
